package com.huarun.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
	public static void main(String[] args) {
		String md5 = getMD5("/send/sendPhoneMessage[\"2020-0608\",\"南京\",\"电梯报警\",\"www.baidu.com\"]ebd828eae7224172a0160cdbad7d0288");
		System.out.println(md5.toUpperCase());
	}

	public static String getMD5(String str, String charset) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes(charset));
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0) {
					i += 256;
				}
				if (i < 16) {
					buf.append("0");
				}
				buf.append(Integer.toHexString(i));
			}
			str = buf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}

	public static String getMD5(String str) {
		return getMD5(str, Constant.CHARSET);
	}

	/**
	 * 签名字符串
	 * 
	 * @param text
	 *            需要签名的字符串
	 * @param sign
	 *            签名结果
	 * @param key
	 *            密钥
	 * @param input_charset
	 *            编码格式
	 * @return 签名结果
	 */
	public static boolean verify(String str, String sign, String charset) {
		String mysign = getMD5(str, charset);
		if (mysign.equals(sign)) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean verify(String str, String sign) {
		String mysign = getMD5(str);
		if (mysign.equals(sign)) {
			return true;
		} else {
			return false;
		}
	}

	public static String getMD5Uppercase(String str) {
		if(!StringUtils.isEmpty(str)){
			return getMD5(str).toUpperCase();
		}
		return "";
	}

	public static String crypt(String str) {
		if (str == null || str.length() == 0) {
			throw new IllegalArgumentException("String to encript cannot be null or zero length");
		}
		StringBuffer hexString = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte[] hash = md.digest();
			for (int i = 0; i < hash.length; i++) {
				if ((0xff & hash[i]) < 0x10) {
					hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
				} else {
					hexString.append(Integer.toHexString(0xFF & hash[i]));
				}
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return hexString.toString();
	}
}
